<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderSn">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单名称" prop="orderName">
        <el-input
          v-model="queryParams.orderName"
          placeholder="请输入订单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:sell_order:add']"
        >新增销售订单</el-button>
      </el-col>
      <el-col :span="1.5">
      <el-button
        type="warning"
        plain
        icon="el-icon-download"
        size="mini"
        @click="handleExport"
        v-hasPermi="['mes:mater_plan:export']"
      >导出</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="sell_orderList"  border style="width: 100%" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" align="center" prop="number"width="90" />
      <el-table-column label="订单状态" align="center" prop="state" width="90" >
        <template v-slot = "scope">
          <dict-tag :options="dict.type.order_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="name" />
      <el-table-column label="订单编号" align="center" width="180px" prop="orderSn" />
      <el-table-column label="订单名称" align="center" prop="orderName" />
      <el-table-column label="订单类型" align="center" prop="orderType" >
        <template slot-scope="scope">
          <span>{{ orderTypeMap.get(scope.row.orderType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签订日期" align="center" prop="signDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交货日期" align="center" prop="deliverDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliverDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务员" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:sell_order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:sell_order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单名称" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入订单名称" style="width: 30%;"/>
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="form.orderType" placeholder="请选择订单类型" style="width: 30%;">
            <el-option
              v-for="item in orderTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="custId">
          <el-select v-model="form.custId" placeholder="请选择客户" style="width: 30%;">
            <el-option
              v-for="item in custList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="title=='修改销售订单'" label="收货人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入" style="width: 30%;" />
        </el-form-item>
        <el-form-item v-if="title=='修改销售订单'" label="联系电话" prop="contactNumber">
          <el-input v-model="form.contactNumber" placeholder="请输入" style="width: 30%;"/>
        </el-form-item>
        <el-form-item v-if="title=='修改销售订单'" label="收货地址" prop="address">
          <el-input v-model="form.address" type = "textarea" placeholder="请输入" style="width: 30%;"/>
        </el-form-item>
        <el-form-item label="签订日期" prop="signDate">
          <el-date-picker clearable
            v-model="form.signDate"
            type="date"
            value-format="yyyy-MM-dd"
            style="width: 30%;"
            placeholder="请选择签订日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交货日期" prop="deliverDate">
          <el-date-picker clearable
            v-model="form.deliverDate"
            type="date"
            value-format="yyyy-MM-dd"
             style="width: 30%;"
            placeholder="请选择交货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="产品信息" >
          <el-button v-if="title=='添加销售订单'" style="margin-bottom: 10px;" type="primary" @click="proorderadd(count)">添 加</el-button>
          <el-card shadow="always" style="border-radius: 15px;">
            <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.proInfoList" >
              <el-table-column label="产品名称" align="center" prop="proId">
                <template slot-scope="scope">

                  <span v-if="title=='修改销售订单'">{{scope.row.proName}}</span>

                  <el-select v-else v-model="scope.row.proId" filterable placeholder="请选择"
                             @change="(option) => prochang(option, scope.$index)">
                    <el-option
                      v-for="item in proList"
                      :key="item.id"
                      :label="item.proName"
                      :value="item.id">
                    </el-option>
                  </el-select>

                </template>
              </el-table-column>
              <el-table-column label="产品编码" align="center" prop="proSn"/>
              <el-table-column label="需求数量" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">

                  <span v-if="title=='修改销售订单'">{{scope.row.deviNum}}</span>

                  <el-input-number v-else id="inputNumber" v-model:value="scope.row.reqNum" :min="0" :precision="0"/>

                </template>
              </el-table-column>
              <el-table-column label="存货单位" align="center" prop="unitName"/>

              <el-table-column v-if="title=='添加销售订单'" label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="proorderadd(scope.$index)"
                             v-hasPermi="['mes:proinfo:edit']">增加</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="proorderdel(scope.$index)"
                             v-hasPermi="['mes:proinfo:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

          </el-card>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listSell_order, getSell_order, delSell_order, addSell_order, updateSell_order, getSell_orderPro } from "@/api/mes/sell_order";
import {listCust_info} from "@/api/mes/cust_info";
import {listPro_design} from "@/api/mes/pro_design";
import {listUnit} from "@/api/mes/unit";
import {addPlan} from "@/api/mes/plan";

export default {
  name: "Sell_order",
  dicts:["order_state"],
  data() {
    return {
      //计数
      count: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售订单表格数据
      sell_orderList: [],
      //客户信息表数据
      custList:[],
      //产品信息表数据
      proList:[],
      //订单产品详情列表
      sellProList:[],
      //单位列表
      unitOptions:[],
      //订单类型选项
      orderTypeOptions:[{
        value: '0',
        label: '销售订单'
      }, {
        value: '1',
        label: '样品订单'
      }, {
        value: '2',
        label: '测试订单'
      }],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSn: null,
        orderName: null,
      },
      // 单位信息查询参数
      queryParamsUnit: {
        unitName: null,
      },
      // 产品信息查询参数
      queryParamsPro: {
        proName: null,
        proType: null,
      },
      // 客户信息查询参数
      queryParamsCust: {
        sn: null,
        name: null,
      },
      // 表单参数
      form: {},
      //创建map
      orderTypeMap: new Map(),
      stateMap:new Map(),
      // 表单校验
      rules: {
        orderSn: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getCustList();
    this.getUnitList();
    this.getProduct();
    this.orderTypeMap.set( 0,'销售订单');
    this.orderTypeMap.set( 1,'样品订单');
    this.orderTypeMap.set( 2,'测试订单');
    this.stateMap.set( 0,'已发布');
    this.stateMap.set( 1,'未发布');

  },
  methods: {
    abcd(adad){
      console.log("dadawda",adad)
    },
    /**
     * 下拉框改变
     * @param {选项值} option
     */
    prochang(option, index) {
      let ss = this.proList.find(item => item.id == option)
      this.form.proInfoList[index].proSn= ss.proSn;
      this.form.proInfoList[index].unitId = ss.unitId;
      this.form.proInfoList[index].proName= ss.proName;
      this.form.proId = ss.id;
      const selectedProduct = this.unitOptions.find(item => item.id == ss.unitId);
      if (selectedProduct) {
        this.form.proInfoList[index].unitName = selectedProduct.unitName;
      }
      console.log(this.form,"产品数组");
    },
    /** 产品信息的删除 */
    proorderdel(index) {
      this.form.proInfoList.splice(index, 1);
      console.log(index,"!!!!!!!!!!!!!!!!!!!!!!")
      this.count=this.count-1
    },
    /** 产品信息的添加 */
    proorderadd(index) {
      if (index != undefined) {
        this.form.proInfoList.splice(index + 1, 0,
          {
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            remark: null,
            proId:null,
            proName:null,
            proSn:null,
            reqNum:0,
            unitId:null,
            unitName:null,
          })
      } else {
        this.form.proInfoList.push(
          {
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            remark: null,
            proId:null,
            proName:null,
            proSn:null,
            reqNum:0,
            unitId:null,
            unitName:null,
          })
      }
      this.count=this.count+1
    },
    /** 查询客户信息列表 */
    getCustList() {
      listCust_info(this.queryParamsCust).then(response => {
        this.custList = response.rows;
        console.log("客户信息列表", this.custList)
      });
    },
    getProduct(){
      listPro_design(this.queryParamsPro).then(response =>{
        this.proList = response.rows;
        console.log('产品选项信息!!!:',this.proList);
      })
    },
    /** 查询单位设计列表 */
    getUnitList() {
      listUnit(this.queryParamsUnit).then(response => {
        this.unitOptions = response.rows;
        console.log("单位选项信息!!!:",this.unitOptions)
      });
    },
    handleChangeCust(){
    // 根据 form.custId 找到对应的存址
          const selectedProduct = this.custList.find(option => option.id === this.form.custId);
          if (selectedProduct) {
            // 更新其他输入框的值
            this.form.contact = selectedProduct.contact;
            this.form.contactNumber = selectedProduct.contactNumber;
            this.form.address = selectedProduct.address;
          }
    },



    /** 查询销售订单列表 */
    getList() {
      this.loading = true;
      listSell_order(this.queryParams).then(response => {
        this.sell_orderList = response.rows;
        this.total = response.total;
        console.log("!!!!!!!!!!!!!",this.sell_orderList)
        this.loading = false;
        this.calculateIndex()
      });
    },
    /** 计算列表编号 */
    calculateIndex() {
      this.sell_orderList.forEach((item, index) => {
        this.$set(item, 'number', index + 1);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        custId: null,
        proId: null,
        orderSn: null,
        orderName: null,
        orderType: null,
        state: null,
        signDate: null,
        deliverDate: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        remark: null,
        contactNumber:null,
        contact:null,
        address:null,
        proInfoList:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销售订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSell_order(id).then(response => {
        this.form = response.data;
        this.form.orderType=String(this.form.orderType)
      });
      getSell_orderPro(id).then(response =>{
        this.form.proInfoList=response.rows;
        console.log("361658146156",this.form.proInfoList)
        this.open = true;
        this.title = "修改销售订单";
        this.handleChangeCust();

      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log("zuizhongshuju!!!!!!!!",this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSell_order(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSell_order(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const orderName = row.orderName || this.orderName
      this.$modal.confirm('是否确认删除销售订单名称为"' + orderName + '"的数据项？').then(function() {
        return delSell_order(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/sell_order/export', {
        ...this.queryParams
      }, `sell_order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
